<template>
  <div class="creator-editor__container">
    <!-- 顶部选项卡 -->
    <div class="creator-editor-header">
      <div class="hb-cpt__pagination hb-cpt__slide-tab line">
        <div class="hb-cpt__pagination-outer">
          <div class="hb-cpt__pagination-inner">
            <button class="slide-tab__tab-item active">
              <div class="slide-tab__tab-label">发布动态</div>
            </button>
            <div class="slide-tab-tab__bar"></div>
          </div>
        </div>
      </div>
    </div>

    <div v-if="isPreviewing" class="preview-modal" @click.self="closePreview">
      <div class="modal-content">
        <img
          :src="currentPreviewImage"
          class="preview-image"
          @click="closePreview"
        />
        <button class="close-btn" @click="closePreview">×</button>
      </div>
    </div>

    <!-- 图文编辑区域 -->
    <div class="hb-page-creator__editor-image-text">
      <div class="editor-image-text__section">
        <!-- 上传图像 -->
        <div class="editor__image-wrapper editor-image-text__image-seletor">
          <div
            v-for="(img, index) in images"
            :key="index"
            class="editor-image-wrapper__box with-hover"
          >
            <img :src="img" alt="预览" />
            <div class="image-overlay">
              <span class="delete-btn" @click="removeImage(index)">×</span>
              <span class="preview-btn" @click="previewImage(index)">预览</span>
              <span class="replace-btn" @click="replaceImage(index)">替换</span>
            </div>
          </div>
          <div
            v-if="images.length < 9"
            class="editor-image-wrapper__box upload"
            @click="handleImageUpload"
            title="点击上传图片"
          >
            <i class="hb-icon">＋</i>
          </div>
        </div>

        <!-- 编辑内容 -->
        <div class="editor-image-text__main-content">
          <!-- 标题 -->
          <div class="hb-cpt__editor-title editor-image-text__title">
            <div class="editor-title__container">
              <div
                class="ProseMirror hb-editor"
                contenteditable="true"
                :data-placeholder="'填写标题'"
                ref="titleRef"
                @input="onTitleInput"
              ></div>
            </div>
            <div class="editor-title__cnt-indicator">{{ titleLength }}/30</div>
          </div>

          <!-- 正文 -->
          <div class="image-text__edit-content">
            <div class="image-text__edit-content--inner">
              <div
                class="ProseMirror hb-editor"
                contenteditable="true"
                :data-placeholder="'正文文案'"
                ref="contentRef"
                @input="onContentInput"
              ></div>
            </div>
          </div>
        </div>

        <!-- 关联模块 -->
        <div class="editor__more-info topics">
          <div class="editor__more-info--left">
            <!-- 将标题和已选话题合并到同一容器 -->
            <div class="topic-header-container">
              <div class="editor__more-info-title">关联话题</div>
              <div class="selected-topics">
                <div
                  v-for="(topic, index) in topics"
                  :key="index"
                  class="selected-topic-item"
                >
                  #{{ topic.topicName }}
                  <span class="remove-topic" @click.stop="removeTopic(index)"
                    >×</span
                  >
                </div>
              </div>
            </div>
            <div class="editor__more-info-desc">{{ topics.length }}/2</div>
          </div>
          <div class="editor__more-info--right">
            <button
              v-if="topics.length < 2"
              class="add-community-btn"
              @click="showModal = true"
            >
              添加话题
            </button>
          </div>
        </div>
        <CommunityTopic
          v-if="showModal"
          :selected-topics="topics"
          @close="showModal = false"
          @add-topic="addTopicToList"
        />
      </div>
    </div>

    <!-- 底部操作区 -->
    <div class="creator-editor__footer">
      <button class="publish-btn" @click="handlePublish">
        {{ isEditing ? '修改' : '立即发布' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import CommunityTopic from './CommunityTopic.vue'
import { uploadAvatarFile } from '@/apis/file.js'
import {
  createDynamic,
  getDynamicDetail,
  updateDynamic,
} from '@/apis/dynamic.js'
import { useRouter, useRoute } from 'vue-router'

const topics = ref([])
const showModal = ref(false)

const images = ref([])
const title = ref('')
const content = ref('')

const titleRef = ref(null)
const contentRef = ref(null)

const isPreviewing = ref(false)
const currentPreviewImage = ref('')

const titleLength = computed(() => title.value.replace(/<[^>]+>/g, '').length)

const onTitleInput = () => {
  title.value = titleRef.value.innerHTML
}

const onContentInput = () => {
  content.value = contentRef.value.innerHTML
}

const handleImageUpload = () => {
  if (images.value.length >= 9) return
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.multiple = true
  input.onchange = () => {
    const files = Array.from(input.files)
    const remaining = 9 - images.value.length
    const filesToAdd = files.slice(0, remaining)

    filesToAdd.forEach((file) => {
      const formData = new FormData()
      formData.append('file', file)

      // 上传文件并获取返回的 URL
      uploadAvatarFile(formData)
        .then((response) => {
          // 假设返回的URL存储在 response.data.url 中
          const imageUrl = response.data
          images.value.push(imageUrl)
        })
        .catch((error) => {
          console.error('上传失败', error)
        })
    })
  }
  input.click()
}

const removeImage = (index) => {
  // 删除图片时，移除对应的 URL
  images.value.splice(index, 1)
}

const replaceImage = (index) => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = () => {
    const file = input.files[0]
    if (!file) return
    const reader = new FileReader()
    reader.onload = (e) => {
      images.value[index] = e.target.result
    }
    reader.readAsDataURL(file)
  }
  input.click()
}
const router = useRouter() // 获取路由实例

const handlePublish = () => {
  // 获取纯文本内容（去除HTML标签）
  const titleText = title.value.replace(/<[^>]+>/g, '').trim()
  const contentText = content.value.replace(/<[^>]+>/g, '').trim()

  // 验证标题（新增）
  if (!titleText) {
    ElMessage.warning('标题不能为空')
    return
  }

  // 验证内容（新增）
  if (!contentText && images.value.length === 0) {
    ElMessage.warning('内容不能为空，请填写文字或添加图片')
    return
  }

  // 验证话题（新增）
  if (topics.value.length === 0) {
    ElMessage.warning('请选择至少一个关联话题')
    return
  }
  const dynamicData = {
    dynamicTitle: title.value,
    dynamicContent: content.value,
    imageUrls: images.value,
    topicIds: topics.value.map((topic) => topic.topicId),
  }

  if (isEditing.value) {
    // ✅ 修改逻辑
    console.log('修改', dynamicData)
    updateDynamic(dynamicId.value, dynamicData)
      .then((response) => {
        if (response.code === '200') {
          ElMessage.success('修改成功')
          router.push('/home/dynamic')
        } else {
          ElMessage.error(response.message || '修改失败')
        }
      })
      .catch((err) => {
        console.error('修改失败:', err)
        ElMessage.error('修改失败')
      })
  } else {
    // ✅ 发布逻辑
    console.log('发布', dynamicData)
    createDynamic(dynamicData)
      .then((response) => {
        if (response.code === '200') {
          ElMessage.success('发布成功')
          router.push('/home/dynamic')
        } else {
          ElMessage.error(response.message || '发布失败')
        }
      })
      .catch((err) => {
        console.error('发布失败:', err)
        ElMessage.error('发布失败')
      })
  }
}

// 预览方法
const previewImage = (index) => {
  currentPreviewImage.value = images.value[index]
  isPreviewing.value = true
}

// 关闭预览
const closePreview = () => {
  isPreviewing.value = false
  currentPreviewImage.value = ''
}

// 键盘事件监听（仅保留ESC关闭）
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape' && isPreviewing.value) {
    closePreview()
  }
})

// 修改添加话题方法
const addTopicToList = (topic) => {
  // 双重校验确保不超过上限
  if (topics.value.length >= 2) return
  // 防止重复添加
  if (!topics.value.some((t) => t.topicId === topic.topicId)) {
    topics.value.push(topic)
  }
}

const removeTopic = (index) => {
  topics.value.splice(index, 1)
}

const isEditing = computed(() => !!dynamicId.value)
const dynamicId = ref(null)
const route = useRoute()

onMounted(async () => {
  const id = route.params.id
  if (id) {
    dynamicId.value = id
    await loadDynamicData(id)
  }
})

async function loadDynamicData(id) {
  const res = await getDynamicDetail(id)
  const data = res.data

  title.value = data.dynamicTitle
  content.value = data.dynamicContent
  images.value = data.imagesUrl // 假设是字符串数组

  // 设置 titleRef / contentRef 的初始内容（注意 innerHTML）
  nextTick(() => {
    if (titleRef.value) titleRef.value.innerHTML = title.value
    if (contentRef.value) contentRef.value.innerHTML = content.value
  })
}
</script>

<style scoped>
.creator-editor__container {
  max-width: 960px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.creator-editor-header {
  margin-bottom: 20px;
}

.hb-cpt__slide-tab {
  display: flex;
  justify-content: space-between;
}

.hb-cpt__pagination-inner {
  display: flex;
  gap: 16px;
  position: relative;
}

.slide-tab__tab-item {
  padding: 10px 18px;
  font-size: 16px;
  background: none;
  border: none;
  cursor: pointer;
  color: #999;
}

.slide-tab__tab-item.active {
  color: #000;
  font-weight: 600;
  border-bottom: 2px solid #007bff;
}

/* 图片区域 */
.editor__image-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 20px;
}

.editor-image-wrapper__box {
  position: relative;
  width: 120px;
  height: 120px;
  background: #f5f5f5;
  border: 1px dashed #ccc;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.editor-image-wrapper__box img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.editor-image-wrapper__box.upload {
  background: #fafafa;
  border: 2px dashed #bbb;
  font-size: 32px;
  color: #999;
  cursor: pointer;
  transition: all 0.2s;
}

.editor-image-wrapper__box.upload:hover {
  background: #f0f0f0;
  border-color: #007bff;
}

.image-overlay {
  display: none;
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.35);
  color: #fff;
  font-size: 12px;
}

.editor-image-wrapper__box.with-hover:hover .image-overlay {
  display: block;
}

.image-overlay span {
  position: absolute;
  padding: 2px 6px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  user-select: none;
}

.image-overlay .delete-btn {
  top: 4px;
  right: 4px;
  font-size: 16px;
  font-weight: bold;
}

.image-overlay .preview-btn {
  bottom: 4px;
  left: 4px;
}

.image-overlay .replace-btn {
  bottom: 4px;
  right: 4px;
}

/* 编辑区域 */
.editor-title__container .ProseMirror {
  min-height: 40px;
  font-size: 16px;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.image-text__edit-content--inner .ProseMirror {
  min-height: 200px;
  font-size: 14px;
  line-height: 1.6;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #fff;
}

.editor-title__cnt-indicator {
  text-align: right;
  font-size: 12px;
  color: #888;
  margin-top: 4px;
}

.editor__more-info {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor__add-btn {
  background: none;
  border: none;
  color: #007bff;
  cursor: pointer;
}

.publish-btn {
  margin-top: 24px;
  background: #000;
  color: #fff;
  padding: 12px 32px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  float: right;
  cursor: pointer;
}

.ProseMirror:empty::before {
  content: attr(data-placeholder);
  color: #aaa;
  font-size: 14px;
}

.add-community-btn {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.add-community-btn:hover {
  background-color: #0056b3;
}

.selected-topic-item {
  background: #f0f2f5;
  padding: 4px 8px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.remove-topic {
  cursor: pointer;
  color: #666;
  font-weight: bold;
  padding-left: 4px;
}

.remove-topic:hover {
  color: #ff4d4f;
}
.topic-header-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.editor__more-info--left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.selected-topics {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin: 0;
}

.editor__more-info-title {
  white-space: nowrap; /* 防止文字换行 */
}

.add-community-btn {
  flex-shrink: 0; /* 防止按钮被压缩 */
}
.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  cursor: zoom-out;
}

.modal-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
  background: transparent; /* 内容区域透明 */
}

.preview-image {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
  border-radius: 8px;
  cursor: zoom-out;
  animation: zoomIn 0.3s ease;
  filter: drop-shadow(0 0 12px rgba(0, 0, 0, 0.2));
}

.close-btn {
  position: absolute;
  top: -30px;
  right: -30px;
  background: rgba(0, 0, 0, 0.7);
  border: none;
  color: white;
  font-size: 24px;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background: rgba(0, 0, 0, 0.9);
  transform: scale(1.1);
}

@keyframes zoomIn {
  from {
    transform: scale(0.9);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}
</style>
